package com.zhulei.biji.suanfa.pace;

import java.util.HashMap;

/**
 * @description:
 * @author: zhulei
 * @create: 2025-03-07 14:37
 **/
public class SubarraySum {
    public static void main(String[] args) {
        int[] nums = {1, -1,2, 0,0,1,-1};
        System.out.println(subarraySum(nums, 0));
    }

    public static int subarraySum(int[] nums, int k) {
        int temp = 0;
        int left = 0;
        int awn = 0;
        int i = 0;
        while (left < nums.length) {
            temp = temp + nums[i];
            if (temp == k) {
                awn++;
            }
            i++;
            if (i >= nums.length) {
                left++;
                i = left;
                temp = 0;
            }
        }
        return awn;
    }

    public static int subarraySum1(int[] nums, int k) {
        int count = 0, pre = 0;
        HashMap<Integer, Integer> mp = new HashMap<>();
        mp.put(0, 1);
        for (int i = 0; i < nums.length; i++) {
            pre += nums[i];
            if (mp.containsKey(pre - k)) {
                count += mp.get(pre - k);
            }
            mp.put(pre, mp.getOrDefault(pre, 0) + 1);
        }
        return count;
    }


}
